package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.exception.StudentExistException;
import org.example.mapper.ClazzMapper;
import org.example.pojo.Clazz;
import org.example.pojo.ClazzQueryParam;
import org.example.pojo.PageResult;
import org.example.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    /**
     * 学生管理-分页查询
     */
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        // 1.设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        //2.执行查询
        List<Clazz> clazzlist = clazzMapper.list(clazzQueryParam);
        clazzlist.forEach(clazz->{
            if(clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开班");
            } else if (clazz.getEndDate().isBefore(LocalDate.now())){
                clazz.setStatus("已结课");
            }else{
                clazz.setStatus("在读中");
            }
        });
        //3.解析结果并封装
        Page<Clazz> p = (Page<Clazz>) clazzlist;
        return new PageResult<Clazz>(p.getTotal(),p.getResult());
    }
    // 模拟检查班级下是否有学生的方法，返回true表示有学生
    private boolean hasStudentsInClass(Integer classId) {
        // 这里应该是实际查询数据库判断班级下是否有学生的逻辑，此处简化为返回true
        Integer i = clazzMapper.find(classId);
        if(i>0){
            return true;
        }else{
            return false;
        }
    } // 模拟检查班级下是否有学生的方法，返回true表示有学生

    @Override
    public void deleteById(Integer id) {
        if (hasStudentsInClass(id)) {
            throw new StudentExistException();
        }
        clazzMapper.deleteById(id);
    }
    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

}
